package rpc.frame.client.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import rpc.frame.core.annotation.RpcRemote;
import rpc.frame.core.proxy.ProxyFactory;
import rpc.frame.core.spring.SpringBeanFactory;

import java.lang.reflect.Field;


/**
 * Bean post 会在初始化 spring bean 流程的时候执行 after 创建完成后执行、Before 创建前执行
 */
@Component
@Slf4j
public class RpcAnnotationProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ProxyFactory proxyFactory;

    /**
     * 设置proxy 从spring 上下文中获取
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.proxyFactory=applicationContext.getBean(ProxyFactory.class);
    }

    /**
     * 1.扫描需要动态代理的 bean
     * 2.进行动态代理
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //获取bean 内的全部字段
        Field[] fields = bean.getClass().getDeclaredFields();
        //检查字段是否 存在RpcRemote 注解
        for (Field field:fields ) {
            RpcRemote rpcRemote = field.getAnnotation(RpcRemote.class);
            if(rpcRemote!=null){
                if(field.isAccessible()){
                    field.setAccessible(true);
                }
                //为该field 生成代理 并且注入
                Object proxy = proxyFactory.newProxyInstance(field.getType());
                if(proxy!=null){
                    try {
                        field.set(bean,proxy);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return bean;
    }
}
